package org.smart4j.chapter4.threadLocal;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

//自己实现ThreadLocal
public class MyThreadLocal<T> {
    //map容器，存放 Thread-T 键值对, 注意必须是 同步Map
    private Map<Thread, T> container = Collections.synchronizedMap(new HashMap<Thread, T>());

    //最好被覆盖
    protected T initialValue(){
        return null;
    }

    public void set(T value){
        container.put(Thread.currentThread(), value);
    }

    public T get(){
        Thread thread = Thread.currentThread();
        T value = container.get(thread);
        if (value == null && !container.containsKey(thread)){
            value = initialValue();
            container.put(thread, value);
        }
        return value;
    }
}
